package com.founder.gateway.oauth.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.setu.framework.jdbc.core.Condition;
import org.setu.framework.jdbc.core.ConditionItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.founder.gateway.oauth.orm.orcl.bean.dto.OrgUserDto;
import com.founder.gateway.oauth.orm.orcl.bean.entity.OrgOrganizationEntity;
import com.founder.gateway.oauth.orm.orcl.bean.entity.OrgUserEntity;
import com.founder.gateway.oauth.service.OAuthService;
import com.founder.gateway.oauth.service.OrgService;
import com.founder.gateway.orm.fzapi.bean.dto.ApiAuthAppDto;
import com.founder.gateway.orm.fzapi.bean.dto.AppInfoDto;
import com.founder.gateway.orm.fzapi.bean.entity.ApiAuthAppEntity;
import com.founder.gateway.orm.fzapi.bean.entity.AppInfoEntity;
import com.founder.gateway.system.bean.CacheStructure;
import com.founder.gateway.system.bean.SetuSession;
import com.founder.gateway.system.consts.Consts;

@Service
public class OAuthServiceImpl implements OAuthService {
    @Autowired
    private OrgService orgService;

    @Override
    @Cacheable(value = CacheStructure.FOUNDER_GATEWAY_API_CACHE, key = "'USER_'+#identity")
    public OrgUserEntity getUserByIdentity(String identity) {
        if (StringUtils.isBlank(identity)) {
            return null;
        }
        OrgUserEntity entity = new OrgUserEntity();
        entity.setXtZxbz(Consts.XT_ZXBZ_WZX);
        entity.setUserid(identity);
        List<OrgUserEntity> list = entity.queryListBySelf(null, 0, 1);
        if (list.isEmpty()) {
            entity = new OrgUserEntity();
            entity.setXtZxbz(Consts.XT_ZXBZ_WZX);
            Condition condition = new Condition();
            condition.add(new ConditionItem(OrgUserDto.ALARM_D, "=", identity));
            condition.add("OR", new ConditionItem(OrgUserDto.IDENTITYCARD_D, "=", identity));
            entity.addConditon(condition);
            list = entity.queryListBySelf(null, 0, 1);
            if (list.isEmpty()) {
                return null;
            }
        }
        return list.get(0);
    }

    @Override
    @Cacheable(value = CacheStructure.FOUNDER_GATEWAY_API_CACHE, key = "'CLIENT_'+#appKey")
    public AppInfoEntity getClientByAppKey(String appKey) {
        Date now = new Date();
        AppInfoEntity entity = new AppInfoEntity();
        entity.setXtZxbz(Consts.XT_ZXBZ_WZX);
        entity.setAppKey(appKey);
        entity.addConditonItem(new ConditionItem(AppInfoDto.add_date, "<=", now));
        entity.addConditonItem(new ConditionItem(AppInfoDto.end_date, ">=", now));
        List<AppInfoEntity> list = entity.queryListBySelf(null, 0, 1);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    @Cacheable(value = CacheStructure.FOUNDER_GATEWAY_API_CACHE, key = "'OAUTH_'+#appId+'_'+#apiSchemeId")
    public boolean checkAuthentication(String appId, String apiSchemeId) {
        Date now = new Date();
        ApiAuthAppEntity entity = new ApiAuthAppEntity();
        entity.setXtZxbz(Consts.XT_ZXBZ_WZX);
        entity.setAppId(appId);
        entity.setApiSchemeId(apiSchemeId);
        entity.addConditonItem(new ConditionItem(ApiAuthAppDto.add_date, "<=", now));
        entity.addConditonItem(new ConditionItem(ApiAuthAppDto.end_date, ">=", now));
        return entity.countBySelf() != 0;
    }

    @Override
    @Cacheable(value = CacheStructure.FOUNDER_GATEWAY_API_CACHE, key = "'SESSION_'+#identity+'_'+#orgCode")
    public SetuSession getSessionBean(String identity, String orgCode) {
        OrgUserEntity userEntity = getUserByIdentity(identity);
        if (userEntity != null) {
            SetuSession session = new SetuSession();

            session.setIndustrialid(userEntity.getAlarm());
            session.setUserId(userEntity.getUserid());
            session.setUserName(userEntity.getUsername());

            OrgOrganizationEntity organizationEntity = new OrgOrganizationEntity();
            List<OrgOrganizationEntity> orgList = organizationEntity.executeForList("select a.* from ORG_ORGANIZATION a,ORG_ORG_USER b " +
                    "where a.XT_ZXBZ = '0' and a.ORGTYPE = '01' and a.ID = b.ORGID  and b.USERID = ?", userEntity.getId());
            if (orgList != null && !orgList.isEmpty()) {
                organizationEntity = orgList.get(0);
                if (StringUtils.isNotBlank(orgCode)) {
                    for (OrgOrganizationEntity org : orgList) {
                        if (orgCode.equals(org.getOrgcode())) {
                            organizationEntity = org;
                            break;
                        }
                    }
                }
                session.setUserOrgCode(organizationEntity.getOrgcode());
                session.setUserOrgName(organizationEntity.getOrgname());

                orgList = orgService.queryParentOrgList(organizationEntity.getId());
                if (orgList != null && !orgList.isEmpty()) {
                    String ssDsjCode = null, ssFsxCode = null, ssPcsCode = null;
                    for (OrgOrganizationEntity org : orgList) {
                        if ("10".equals(org.getOrglevel())) {
                            ssDsjCode = org.getOrgcode();
                        } else if ("21".equals(org.getOrglevel())) {
                            ssFsxCode = org.getOrgcode();
                        } else if ("32".equals(org.getOrglevel())) {
                            ssPcsCode = org.getOrgcode();
                        }
                    }
                    if (ssFsxCode == null) {
                        orgCode = StringUtils.trimToEmpty(organizationEntity.getOrgcode());
                        if (!orgCode.startsWith("00", 4) && orgCode.length() >= 6 && !orgCode.endsWith("000000")) {
                            orgCode = orgCode.substring(0, 6) + "000000";
                            organizationEntity = orgService.queryByOrgCode(orgCode);
                            if (organizationEntity != null) {
                                ssFsxCode = organizationEntity.getOrgcode();
                            }
                        }
                    }
                    session.setSsDsjCode(StringUtils.trimToEmpty(ssDsjCode));
                    session.setSsFsxCode(StringUtils.trimToEmpty(ssFsxCode));
                    session.setSsPcsCode(StringUtils.trimToEmpty(ssPcsCode));
                }
            }
            return session;
        }
        return null;
    }
}
